//
//  ViewController.m
//  QQLogin
//
//  Created by 伍银荣 on 2017/6/15.
//  Copyright © 2017年 WYR. All rights reserved.
//

#import "ViewController.h"
#import <TencentOpenAPI/TencentOAuth.h>

@interface ViewController ()<TencentSessionDelegate>
{
    UIButton *openBtn;
    TencentOAuth *tencentOAut;
    NSArray *premissions; //权限
    UILabel *resultLabel;
    UILabel *TokenLabel;
}

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    //1.初始化控件
    openBtn = [UIButton buttonWithType:UIButtonTypeRoundedRect];
    openBtn.frame = CGRectMake(100, 50, 60, 60);
    [openBtn setTitle:@"QQ登录" forState:UIControlStateNormal];
    [openBtn addTarget:self action:@selector(openBtnclick) forControlEvents:UIControlEventTouchDown];
    [self.view addSubview:openBtn];
    
    resultLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 100, 300, 36)];
    resultLabel.text = @"我是结果";
    [self.view addSubview:resultLabel];
    
    TokenLabel = [[UILabel alloc]initWithFrame:CGRectMake(30, 160, 300, 60)];
    TokenLabel.text = @"我是token";
    TokenLabel.numberOfLines = 0;
    [self.view addSubview:TokenLabel];
    
   tencentOAut =[[TencentOAuth alloc]initWithAppId:@"1106152137" andDelegate:self];
    
    //设置权限列表，需要什么添加什么
    premissions = [NSArray arrayWithObjects:@"get_user_info",@"get_simple_userinfo",@"add_t",nil];
}

-(void)openBtnclick
{
    [tencentOAut authorize:premissions inSafari:NO];
}

//登录完成调用
-(void)tencentDidLogin
{
    resultLabel.text = @"登录成功";
    if (tencentOAut.accessToken && 0 !=[tencentOAut.accessToken length]) {
        //记录用户的open，ID和token过期时间
        TokenLabel.text = tencentOAut.accessToken;
        [tencentOAut getUserInfo];
    }else{
        resultLabel.text = @"登录失败，没有获取到accessToken";
    }
}

//非网络错误导致的登录失败
-(void)tencentDidNotLogin:(BOOL)cancelled
{
    if (cancelled) {
        resultLabel.text = @"用户登录取消";
    }else{
        resultLabel.text = @"登录失败";
    }
}

//网络错误导致的登录失败
-(void)tencentDidNotNetWork
{
    resultLabel.text = @"网络错误，请检查网络设置";
}

//登录用户信息方法
-(void)getUserInfoResponse:(APIResponse *)response
{
    NSLog(@"response = %@",response);
    resultLabel.text = [NSString stringWithFormat:@"你好,%@",[response.jsonResponse objectForKey:@"nickname"]];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
